package com.zb.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.regexp.internal.RE;
import com.zb.client.SkuFeignClient;
import com.zb.dto.SkuDTO;
import com.zb.entity.TbOrderItemModel;
import com.zb.entity.TbOrderModel;
import com.zb.mapper.TbOrderMapper;
import com.zb.service.CartService;
import com.zb.service.TbOrderItemService;
import com.zb.service.TbOrderService;
import com.zb.vo.BuyGoodsVO;
import com.zb.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @date:2024/11/6 19:06 星期三
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper,TbOrderModel> implements TbOrderService {


    @Autowired
    private CartService cartService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbOrderItemService orderItemService;
    @Autowired
    private SkuFeignClient skuFeignClient;
    @Override
    public Boolean createOrder(OrderVO orderVO) {
        //去购物车查找，用户选择购买的商品列表
        List<TbOrderItemModel> itemList = cartService.select(orderVO.getUsername(), orderVO.getSkuIds());
        //创建订单对象
        TbOrderModel orderModel = new TbOrderModel();
        BeanUtils.copyProperties(orderVO,orderModel);
        orderModel.setId(IdWorker.getIdStr());
        //声明总金额和总数量
        Integer totalMoney = 0;
        Integer totalNum = 0;
        //遍历购物车选中的商品
        for (TbOrderItemModel orderItemModel : itemList) {
            //远程调用商品信息
            SkuDTO skuDTO = skuFeignClient.info(orderItemModel.getSkuId());
            totalMoney += skuDTO.getPrice() * orderItemModel.getNum();
            totalNum += orderItemModel.getNum();
            //添加订单详情;
            orderItemModel.setId(IdWorker.getIdStr());
            orderItemModel.setSkuId(skuDTO.getId());
            orderItemModel.setOrderId(orderModel.getId());
            orderItemModel.setName(skuDTO.getName());
            orderItemModel.setPrice(skuDTO.getPrice());
            orderItemModel.setMoney(skuDTO.getPrice() * orderItemModel.getNum());
            orderItemModel.setImage(skuDTO.getImage());
            orderItemModel.setWeight(skuDTO.getWeight());
            orderItemService.save(orderItemModel);
            //远程调用修改商品库存
            skuFeignClient.updateNum(skuDTO.getId(), orderItemModel.getNum());
        }

        orderModel.setTotalMoney(totalMoney);
        orderModel.setTotalNum(totalNum);
        boolean save = this.save(orderModel);
        //清除购物车中选中的商品信息
        redisTemplate.boundHashOps("cart:"+orderVO.getUsername())
                .delete(orderVO.getSkuIds());
        return save;
    }
}
